<?php
// +----------------------------------------------------------------------
// | Copyright © Sogu Technologies Co. Ltd 2018-2050 All rights reserved.
// +----------------------------------------------------------------------
// | File name: RiskCommand.php
// +----------------------------------------------------------------------
// | Author: gxs
// +----------------------------------------------------------------------
// | Description: 风控command
// +----------------------------------------------------------------------
// | Others: 其他内容的说明
// +----------------------------------------------------------------------
// | History: 修改历史记录列表，每条修改记录应包含修改日期、修改者及修改内容简述
// +----------------------------------------------------------------------
// | 1.Date: 2019/1/29 Author: gxs Modification: 创建
// +----------------------------------------------------------------------

namespace App\Console\Commands;

use App\Events\RiskResultEvent;
use App\Facades\RiskPlatformRequestFacade;
use App\Jobs\CheckSpiderJob;
use App\Jobs\QueryRiskJob;
use App\Jobs\RiskAlipayCacheJob;
use App\Jobs\RiskSpiderCacheJob;
use App\Models\UserApplyRiskLog;
use App\Jobs\AliPayJob;
use App\Jobs\RiskReptileJob;
use App\Models\UserAuthSpiderTransLog;
use App\Models\UserDeviceInfo;
use App\Models\UserLoanRequest;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class RiskCommand extends Command {
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'risk:cron {action : test|reptile|alipay|checkSpiderStatus|queryRiskResult|cacheReptile|cacheAlipay}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Risk cron relevant';

    /**
     * The console command action. test
     *
     * @var string
     */
    protected $action;

    /**
     * Description: 缓存运营商
     * Author: luwei
     * DateTime: 2019-01-29 15:43
     */
    public function cacheReptile(){
        $list = UserAuthSpiderTransLog::with(['loanRequest'])
            ->where('status', '=', UserAuthSpiderTransLog::STATUS_INIT)
            ->whereHas('loanRequest',function($query){
                $query->where('current',1);
            })
            ->where('type','carrier')
            ->get()
            ->toArray();
        if (!empty($list)) {
            $ids = array_column($list, 'id');
            foreach (UserAuthSpiderTransLog::whereIn('id', $ids)->where('trade_no','<>','')->cursor() as $model) {
                $res = UserAuthSpiderTransLog::canSpider($model->loan_request_id,true);
                $trade_no = $model->trade_no;
                if($res && $trade_no){
                    RiskSpiderCacheJob::dispatch($model,UserAuthSpiderTransLog::TYPE_CARRIER);
                }
            };
        }
        $this->info('risk reptile cache done');
    }

    /**
     * Description: 缓存芝麻分
     * Author: luwei
     * DateTime: 2019-01-29 15:43
     */
    public  function  cacheAlipay()
    {
        $list =  UserAuthSpiderTransLog::with(['loanRequest'])
            ->where('status', '=', UserAuthSpiderTransLog::STATUS_INIT)
            ->whereHas('loanRequest',function($query){
                $query->where('current',1);
            })
            ->where('type','alipay')
            ->get()
            ->toArray();
        if(!empty($list)){
            $ids = array_column($list, 'id');
            foreach (UserAuthSpiderTransLog::whereIn('id', $ids)->where('trade_no','<>','')->cursor() as $key => $model) {
                $res = UserAuthSpiderTransLog::canSpider($model->loan_request_id,true);
                $trade_no = $model->trade_no;
                if($res && $trade_no){
                    RiskSpiderCacheJob::dispatch($model,UserAuthSpiderTransLog::TYPE_ZHIMA);
                }
            }
        }
        $this->info('alipay risk cache done');
    }

    /**
     * Description: 爬虫状态查询接口
     * Author: Gxs
     */
    public function reptile()
    {
        ini_set('memory_limit', '2048M');
        set_time_limit(0);
        $list =  UserAuthSpiderTransLog::with(['loanRequest'])
            ->where('status', UserAuthSpiderTransLog::STATUS_INIT)
            ->whereHas('loanRequest',function($query){
                $query->where('current',1);
            })
            ->where('type','carrier')
            ->get()->toArray();
        if(!empty($list)){
            $ids = array_column($list, 'id');
            foreach (UserAuthSpiderTransLog::whereIn('id', $ids)->where('trade_no','<>','')->cursor() as $key => $model) {
                $res = UserAuthSpiderTransLog::canSpider($model->loan_request_id);
                $trade_no = $model->trade_no;
                if($res && $trade_no){
                    RiskReptileJob::dispatch($model);
                }
            }
        }
        $this->info('risk reptile done');
    }

    /**
     * 检测爬虫是否成功并提交风控
     * @return bool
     * @author luwei
     * @date 2019-01-29 14:11
     */
    public function checkSpiderStatus() {
        $loanIds = UserLoanRequest::select('id')->where('current',1)->byStatus(UserLoanRequest::STATUS_WAIT_FOR_RISK)->get()->pluck('id')->toArray();

//        $trans = UserAuthSpiderTransLog::whereIn('loan_request_id',$loanIds)
//            ->groupBy('loan_request_id')
//            ->having('status',UserAuthSpiderTransLog::STATUS_SUCCESS)
//            ->get();
        $transCarrier = UserAuthSpiderTransLog::whereIn('loan_request_id',$loanIds)
            ->where('type',UserAuthSpiderTransLog::TYPE_CARRIER_ENG)
            ->where('status',UserAuthSpiderTransLog::STATUS_SUCCESS)
            ->get()
            ->pluck('loan_request_id')
            ->toArray();

        $transAli = UserAuthSpiderTransLog::whereIn('loan_request_id',$loanIds)
            ->where('type',UserAuthSpiderTransLog::TYPE_ALIPAY_ENG)
            ->where('status',UserAuthSpiderTransLog::STATUS_SUCCESS)
            ->get()
            ->pluck('loan_request_id')
            ->toArray();

        $all = array_intersect($transCarrier,$transAli);
        $trans = UserAuthSpiderTransLog::whereIn('loan_request_id',$all)->groupBy('loan_request_id')->get();
        foreach ($trans as $tran){
            $c = UserAuthSpiderTransLog::where('type',UserAuthSpiderTransLog::TYPE_CARRIER_ENG)->where('status',UserAuthSpiderTransLog::STATUS_RISK_OK)->where('id',$tran->id)->count();
            $a = UserAuthSpiderTransLog::where('type',UserAuthSpiderTransLog::TYPE_ALIPAY_ENG)->where('status',UserAuthSpiderTransLog::STATUS_RISK_OK)->where('id',$tran->id)->count();
            if($a||$c){
                continue;
            }
            $flag = UserAuthSpiderTransLog::byLoanRequestId($tran->loan_request_id)->update(['status' => UserAuthSpiderTransLog::STATUS_RISK_OK]);
            \Log::info('检测爬虫数据源:'.json_encode($tran,JSON_UNESCAPED_UNICODE));
            if($flag){
                CheckSpiderJob::dispatch($tran);
            }
        }
        return true;
    }

    /**
     * 风控结果查询
     * @author luwei
     * @date 2019-01-29 16:19
     */
    public function queryRiskResult() {
        $status = [
            UserApplyRiskLog::STATUS_DEFAULT,
            UserApplyRiskLog::STATUS_PROCESSING
        ];
        $risk   = UserApplyRiskLog::whereIn('status', $status)->get();
        \Log::info('风控数据源:'.json_encode($risk,JSON_UNESCAPED_UNICODE));
        foreach ($risk as $v) {
            QueryRiskJob::dispatch($v);
        }
        return true;
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->initAction();
        $this->runAction();
    }

    /**
     * Description: Initialize command action.
     * Author: Gxs
     */
    protected function initAction()
    {
        $this->action = $this->argument('action');

        if (!in_array($this->action, ['reptile','alipay','checkSpiderStatus','queryRiskResult','cacheReptile','cacheAlipay'])) {
            $this->error("Invalid argument '{$this->action}'. Expected 'reptile'.");
            exit(1);
        }
    }

    /**
     * Description: Run action.
     * Author: Gxs
     */
    protected function runAction()
    {
        $this->{$this->action}();
    }

    /**
     * Description: 获取支付宝爬虫结果
     * Author: liuju
     * DateTime: 2019-01-29 15:43
     */
    public  function  alipay()
    {
        ini_set('memory_limit', '2048M');
        set_time_limit(0);
        $list =  UserAuthSpiderTransLog::with(['loanRequest'])
            ->where('status', UserAuthSpiderTransLog::STATUS_INIT)
            ->whereHas('loanRequest',function($query){
                $query->where('current',1);
            })
            ->where('type','alipay')
            ->get()->toArray();
         if(!empty($list)){
             $ids = array_column($list, 'id');
             foreach (UserAuthSpiderTransLog::whereIn('id', $ids)->where('trade_no','<>','')->cursor() as $key => $model) {
                 $res = UserAuthSpiderTransLog::canSpider($model->loan_request_id);
                 $trade_no = $model->trade_no;
                 if($res && $trade_no){
                    AliPayJob::dispatch($model);
                 }
             }
         }
        $this->info('alipay risk done');
    }
}